package com.example.tourpal;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.TextView;
import android.widget.Toast;

import com.example.tourpal.model.LocalDataLoader;
import com.example.tourpal.model.LocalDataLoader.SquareLishenter;
import com.example.tourpal.model.Page;
import com.example.tourpal.model.Person;
import com.example.tourpal.widget.DynamicListView;
import com.example.tourpal.widget.DynamicListView.DynamicListViewListener;
import com.example.tourpal.widget.HomePlanAdapter;

public class PlanSearchActivity extends Activity implements
		DynamicListViewListener {

	private static final String UNDER_LINE = "-";

	private Context context;

	private SearchView planSearch;
	private ImageView back;
	private DynamicListView searchPlanListView;

	// Data
	private HomePlanAdapter searchPlanAdapter;
	private List<HashMap<String, Object>> resultPlanList;
	private int currentPage = 1;
	// private int currentItem = 0;
	// private int allPage = 0;
	// private int allItem = 0;

	private String searchText;

	private SimpleDateFormat sFormat;
	private SimpleDateFormat tFormat;

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				if (searchPlanAdapter != null) {
					searchPlanAdapter = null;
				}
				searchPlanAdapter = new HomePlanAdapter(context,
						resultPlanList, false);
				searchPlanListView.setAdapter(searchPlanAdapter);
				searchPlanListView.doneRefresh();
				Toast.makeText(PlanSearchActivity.this,
						"Loading " + msg.arg1 + " Dates.", Toast.LENGTH_LONG)
						.show();

				searchPlanListView.setSelection(0);
			} else if (msg.what == 1) {
				searchPlanAdapter.notifyDataSetChanged();
				searchPlanListView.doneMore();
				Toast.makeText(PlanSearchActivity.this,
						"More " + msg.arg1 + " Dates.", Toast.LENGTH_LONG)
						.show();

				searchPlanListView.setSelection((currentPage - 1) * 20);
			} else {
				super.handleMessage(msg);
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		context = this;

		setContentView(R.layout.plan_search_view);

		sFormat = new SimpleDateFormat(getText(R.string.date_format_1)
				.toString(), Locale.getDefault());
		tFormat = new SimpleDateFormat(getText(R.string.date_format_2)
				.toString(), Locale.getDefault());

		searchPlanListView = (DynamicListView) findViewById(R.id.searchPlan);
		planSearch = (SearchView) findViewById(R.id.seracher);
		try {
			Class<?> argClass = planSearch.getClass();
			Field mSearchHintIconField = argClass
					.getDeclaredField("mSearchHintIcon");
			mSearchHintIconField.setAccessible(true);
			ImageView mSearchHintIcon = (ImageView) mSearchHintIconField
					.get(planSearch);
			mSearchHintIcon.setVisibility(View.VISIBLE);

			Field ownField = argClass.getDeclaredField("mSearchPlate");
			ownField.setAccessible(true);
			View mView = (View) ownField.get(planSearch);
			mView.setBackground(context.getResources().getDrawable(
					R.drawable.search_bar_bg));

			int id = planSearch.getContext().getResources()
					.getIdentifier("android:id/search_src_text", null, null);
			TextView textView = (TextView) planSearch.findViewById(id);
			textView.setPadding(0, 30, 0, 0);
			textView.setTextSize(15);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		planSearch.setOnQueryTextListener(new OnQueryTextListener() {

			@Override
			public boolean onQueryTextSubmit(String text) {
				if (text.trim().equals("")) {
					Toast.makeText(context, "Search for nothing.",
							Toast.LENGTH_LONG).show();
					return false;
				}
				searchText = text;
				doSearch(1, searchText, 0);
				return false;
			}

			@Override
			public boolean onQueryTextChange(String arg0) {
				// TODO Auto-generated method stub
				return false;
			}
		});

		searchPlanListView.setAdapter(searchPlanAdapter);
		searchPlanListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> av, View v, int index, long l) {

				if (index == 1) {
					return;
				}
				Intent intent = new Intent();
				intent.setClass(context, PlanOverViewActivity.class);

				Bundle bundle = new Bundle();
				bundle.putSerializable("planID", v.getId());
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});

		searchPlanListView.setDoMoreWhenBottom(false);
		searchPlanListView.setOnRefreshListener(this);
		searchPlanListView.setOnMoreListener(this);

		back = (ImageView) findViewById(R.id.back);
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
	}

	protected void doSearch(int index, String text, final int doType) {
		if (doType == 0) {
			resultPlanList = null;
			resultPlanList = new ArrayList<HashMap<String, Object>>();
			resultPlanList.add(new HashMap<String, Object>());
		}

		LocalDataLoader loader = new LocalDataLoader(context);
		loader.startQuerySquareData(index, new SquareLishenter() {

			@Override
			public void requestSquareList(List<Person> persons, Page page) {

				List<HashMap<String, Object>> tempList = new ArrayList<HashMap<String, Object>>();

				for (Person person : persons) {
					HashMap<String, Object> itemHashMap = new HashMap<String, Object>();

					itemHashMap.put("planId", person.getJourneyId());
					itemHashMap.put("headPic", R.drawable.ic_launcher);
					itemHashMap.put("followSign", person.isIspublic());
					itemHashMap.put("planName", person.getName());
					try {
						String start = tFormat.format(sFormat.parse(person
								.getStartTime()));
						String end = tFormat.format(sFormat.parse(person
								.getEndTime()));
						itemHashMap.put("planDate", start + UNDER_LINE + end);
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					itemHashMap.put("planHint", person.getDestination());
					itemHashMap.put("goodCnt", person.getPraiseNum());
					itemHashMap.put("commentCnt", person.getCommentNum());
					tempList.add(itemHashMap);
				}

				synchronized (resultPlanList) {
					resultPlanList.addAll(tempList);
				}

				handler.sendMessage(handler.obtainMessage(doType,
						tempList.size(), 0));
				// handler.sendEmptyMessage(doType);

				if (page != null) {
					// allPage = page.getPageCount();
					Log.e("YLQ", "PageNo:" + page.getPageNo());
					// currentItem = page.getPageSize();
					// allItem = page.getRowCount();
				}

			}

		}, text);
	}

	@Override
	public boolean onRefreshOrMore(DynamicListView dynamicListView,
			boolean isRefresh) {
		if (!isNetworkAvailable()) {
			searchPlanListView.doneRefresh();
			searchPlanListView.doneMore();
		}

		if (isRefresh) {
			doSearch(1, searchText, 0);

		} else {
			Log.e("YLQ", "currentPage=" + currentPage);
			currentPage++;
			doSearch(currentPage, searchText, 1);

		}
		return false;
	}

	public boolean isNetworkAvailable() {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm == null) {
		} else {// cm.getActiveNetworkInfo().isAvailable();
			NetworkInfo[] info = cm.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();

		overridePendingTransition(R.anim.main_enter, R.anim.sub_exit);
	}
}
